/* eslint-disable no-unused-vars */
import axios from 'axios'
import router from '../router'
import {Message} from 'element-ui'

const service = axios.create({
  timeout: 5000,
  baseURL: process.env.SERVER_URL + window.location.pathname,
})

service.interceptors.request.use(config => {
  return config
}, error => {
  Promise.reject(error)
})

service.interceptors.response.use(response => {
  // Do something with response data
  // blob格式请求
  if (response.config.responseType === 'blob') {
    return response.data
  }
  if (response.data.code === 0) {
    Message.error({message: '请先登录'})
    router.push('/')
    return {}
  }
  if (response.data.code === 400) {
    Message.error(response.data.msg)
    return {}
  }
  if (response.data.code === 200) {
    let data = response.data.data || response.data.content || []
    let res = null
    if (Array.isArray(data)) {
      if (data.length === 0) {
        res = []
      }
      if (data.length > 1) {
        res = data
      }
      if (data.length === 1) {
        if (Array.isArray(data[0])) { // 二维数组
          res = data
        } else { // 非二维数组
          res = data[0]
        }
      }
    } else {
      res = data
    }
    return res
  }
}, error => {
  // Do something with response error
  Message.error('请求失败，请刷新页面重试')
  return Promise.reject(error)
})

/**
 * get请求
 * @param url {string} 请求地址
 * @param params {object} [params={}] 请求参数
 * @param config {object} [config={}] 请求配置
 * @returns {Promise<AxiosResponse<T>>}
 */
function get (url, params = {}, config = {}) {
  return service.get(url, {params, ...config})
}

/**
 * post请求
 * @param url {string} 请求地址
 * @param data {object} [data={}] 请求参数
 * @param config {object} [config={}] 请求配置
 * @returns {Promise<AxiosResponse<T>>}
 */
function post (url, data = {}, config = {}) {
  const accessToken = window.localStorage.getItem('access_token')
  return service.post(url, {access_token: accessToken, ...data}, config)
}

const request = {get, post}

export default request
